package com.chatroomdemo.service;

import com.chatroomdemo.mapper.MessageMapper;
import com.chatroomdemo.mapper.SessionMapper;
import com.chatroomdemo.model.Friend;
import com.chatroomdemo.model.MessageSession;
import com.chatroomdemo.model.MessageSessionUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SessionService {
    @Autowired
    private SessionMapper sessionMapper;

    @Autowired
    private MessageMapper messageMapper;
    public List<MessageSession> getSessionList(Integer userId) {

        List<MessageSession> messageSessionList = new ArrayList<MessageSession>();
        //根据userId查询sessionIds
        List<Integer> sessionIds = sessionMapper.selectSessionIdByUserId(userId);

        //将sessionIds和friends两个列表的值合并到list
        for (int i = 0; i < sessionIds.size(); i++) {
            Integer sessionId = sessionIds.get(i);
            //1、根据会话查找好友
            List<Friend> friends = sessionMapper.selectFriendBySessionId(sessionId,userId);
            //2.获取会话最后一条消息
            String lastMessage = messageMapper.getLastMessageBySessionId(sessionId);
            //如果该会话没有消息，设为空
            if(lastMessage == null){
                lastMessage = "";
            }

            //将会话id 、 会话中的好友 、 每个会话的最后一条信息放到list
            messageSessionList.add(new MessageSession(sessionId, friends,lastMessage));
        }

        return messageSessionList;
    }

    public Integer insertMessageSession(MessageSession messageSession) {
        return sessionMapper.insertMessageSession(messageSession);
    }

    public void insertMessageSessionUser(MessageSessionUser messageSessionUser) {
        sessionMapper.insertMessageSessionUser(messageSessionUser);
    }
}
